/**
 * Created by 岸芷汀翎 on 2017/2/2.
 */
function getUrlParameter(param) { // 获取Url上的参数
  var query = window.location.search;
  var iLen = param.length;
  var iStart = query.indexOf(param);
  if (iStart == -1)
    return "";
  iStart += iLen + 1;
  var iEnd = query.indexOf("&", iStart);
  if (iEnd == -1)
    return query.substring(iStart);
  return query.substring(iStart, iEnd);
}
function setResizeByIdAndHeight(id, height) {
  var wh = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) ||
      document.body.clientHeight
  var vid = document.getElementById(id)
  if (vid) {
    vid.style.height = (wh - vid.offsetTop - height) + 'px'
  }
}
function formatTime(time) {
  if(moment){
    return moment(time).format("YYYY-MM-DD HH:mm:ss");
  }
  return '';
}
var websocketRoot = "ws://" + window.location.host;
console.log("websocketRoot:", websocketRoot);
var websocketTool = {
  chatUri: websocketRoot + "/im/",
  assistUri: websocketRoot + "/imAssist",
  user: {},
  friends: [],
  groups: [],
  onlineStatus: 1,
  socket: {},
  checkSocket: {},
  userInfoMap: {},
  groupMap: {},
  init: function (user, friends, groups) {
    var that = this;
    this.friends = friends;
    this.friends.forEach(function (fr) {
      that.userInfoMap[fr.id] = fr;
    });
    this.user = user;
    this.groups = groups;
    this.groups.forEach(function (group) {
      that.groupMap[group.id] = group;
    });
    this.chatUri += user.id;
    this.resetSocket();
    var sendCheckMessage = function () {
      that.friends.forEach(function (friend) {
        if (that.checkSocket.readyState == 1) {
          that.checkSocket.send(friend.id);
        } else {
          if (that.onlineStatus == 1) {
            that.checkAndSetStatus();
          }
        }
      });
      setTimeout(sendCheckMessage, 2000);
    };
    setTimeout(sendCheckMessage, 2000);
  },
  resetSocket: function () {
    var that = this;
    this.checkSocket = new WebSocket(this.assistUri);
    this.socket = new WebSocket(this.chatUri);
    this.socket.onopen = function (event) {
      that.sendMessage({});
      that.checkAndSetStatus();
    };
    this.socket.onerror = function (e) {
      console.error('websocket is error:', e, socket);
      that.checkAndSetStatus();
    };
    this.checkSocket.onopen = function (event) {
      console.log('the checkSocket is open..............')
    };
    this.checkSocket.onmessage = function (event) {
      var message = JSON.parse(event.data);
      var userInfo = that.userInfoMap[message.id];
      if (userInfo && typeof userInfo.setFriendStatus == "function") {
        userInfo.setFriendStatus(message.id, message.online);
      }
    };
    this.socket.onmessage = function (event) {
      var message = JSON.parse(event.data);
      if (message.sendType == "LEAVE") {
        that.socket.close();
        that.checkSocket.close();
        alert("被他人挤下线！！");
        that.onlineStatus = 0;
        that.notOnlineEvent();
      } else {
        console.log('onmessage.message:', message);
        var mes = {
          name: message.userName
          , id: message.userId
          , type: 'friend'
          , content: message.content
          , timestamp: message.timeStamp
        };
        if (message.type == 'GROUP') {
          mes.type = 'group';
          mes.groupname = message.sendName;
          mes.id = message.sendId;
          var group = that.groupMap[message.sendId];
          if (group && typeof group.getMessage == "function") {
            group.getMessage(mes);
          }
        } else {
          var userInfo = that.userInfoMap[message.userId];
          if (userInfo && typeof userInfo.getMessage == "function") {
            userInfo.getMessage(mes);
          }
        }
      }
    };
  },
  sendMessage: function (message) {
    var data = {
      user: this.user,
      message: message
    };
    if (message.type == 1) {
      data.groupIds = this.groupMap[message.sendId].list;
    }
    this.socket.send(JSON.stringify(data));
  },
  checkAndSetStatus: function () {
    if (this.socket.readyState == 1) {
      this.onlineStatus = 1;
      this.onlineEvent();
    } else {
      this.onlineStatus = 0;
      this.notOnlineEvent();
    }
  },
  setOnlineStatus: function (status) {
    if (status != this.user.onlineStatus) {
      this.user.status = parseInt(status);
      if (status == 1 && this.user.status == 0) {
        this.resetSocket();
      } else if (status == 0) {
        this.socket.close();
        this.checkSocket.close();
      } else {
        this.sendMessage({});
      }
    }
  },
  onlineEvent: function () {

  },
  notOnlineEvent: function () {

  }
};